package com.lanmaoly.web.server.controller;

import com.alibaba.fastjson.JSON;
import com.lanmaoly.web.common.utils.CookieUtil;
import com.lanmaoly.web.server.entity.Result;
import com.lanmaoly.web.server.pojo.group.Cart;
import com.lanmaoly.web.server.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Controller
@RequestMapping(value = "cart")
public class CartController {

    @RequestMapping(value = "home")
    public String home(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        if ("anonymousUser".equals(name)) {
            model.addAttribute("isLogin", false);
        } else {
            model.addAttribute("username", authentication.getName());
            model.addAttribute("isLogin", true);
        }
        return "portal/cart";
    }

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private CartService cartService;

    @RequestMapping("/findCartList")
    @ResponseBody
    public List<Cart> findCartList() {
        //当前登录人账号
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        log.info("当前登录人：{}", username);

        String cartListString = CookieUtil.getCookieValue(request, "cartList", "UTF-8");
        if (cartListString == null || "".equals(cartListString)) {
            cartListString = "[]";
        }
        List<Cart> cartList_cookie = JSON.parseArray(cartListString, Cart.class);

        if ("anonymousUser".equals(username)) {
            //如果未登录
            //从cookie中提取购物车
            log.info("从cookie中提取购物车");

            return cartList_cookie;
        } else {
            //如果已登录
            //获取redis购物车
            List<Cart> cartList_redis = cartService.findCartListFromRedis(username);
            if (cartList_cookie.size() > 0) {
                //判断当本地购物车中存在数据
                //得到合并后的购物车
                List<Cart> cartList = cartService.mergeCartList(cartList_cookie, cartList_redis);
                //将合并后的购物车存入redis
                cartService.saveCartListToRedis(username, cartList);
                //本地购物车清除
                CookieUtil.deleteCookie(request, response, "cartList");
                log.info("执行了合并购物车的逻辑");
                return cartList;
            }
            return cartList_redis;
        }

    }

    //    @CrossOrigin(origins = "http://localhost:9105")
    @RequestMapping("addGoodsToCartList")
    @ResponseBody
    public Result addGoodsToCartList(Long itemId, Integer num) {

        //response.setHeader("Access-Control-Allow-Origin", "http://localhost:9105");//可以访问的域(当此方法不需要操作cookie)
        //response.setHeader("Access-Control-Allow-Credentials", "true");//如果操作cookie，必须加上这句话

        //当前登录人账号
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        log.info("当前登录人：{}", name);

        try {
            //提取购物车
            List<Cart> cartList = findCartList();
            //调用服务方法操作购物车
            cartList = cartService.addGoodsToCartList(cartList, itemId, num);

            if ("anonymousUser".equals(name)) {
                //如果未登录
                //将新的购物车存入cookie
                String cartListString = JSON.toJSONString(cartList);
                CookieUtil.setCookie(request, response, "cartList", cartListString, 3600 * 24, "UTF-8");
                log.info("向cookie存储购物车");
            } else {
                //如果登录
                cartService.saveCartListToRedis(name, cartList);
            }
            return new Result(true, "存入购物车成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "存入购物车失败");
        }
    }
}
